package com.edu.cdp.service.impl;

import com.edu.cdp.DTO.PageDTO;
import com.edu.cdp.VO.OrderDetailsVO;
import com.edu.cdp.VO.OrderPaymentVO;
import com.edu.cdp.VO.OrderVO;
import com.edu.cdp.common.PageResult;
import com.edu.cdp.domain.User;
import com.edu.cdp.mapper.GoodsMapper;
import com.edu.cdp.mapper.OrderDetailsMapper;
import com.edu.cdp.mapper.UserMapper;
import com.edu.cdp.service.CommonService;
import com.edu.cdp.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.cdp.domain.Orders;
import com.edu.cdp.service.OrdersService;
import com.edu.cdp.mapper.OrdersMapper;
import com.edu.cdp.utils.NumberUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author Yang Can
* @description 针对表【orders】的数据库操作Service实现
* @createDate 2024-06-03 14:29:02
*/
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    OrderDetailsMapper orderDetailsMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserService userService;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    CommonService commonService;

    @Override
    public PageResult pageQuery(PageDTO pageDTO) {
        Page<Orders> orders = new Page<Orders>(pageDTO.getPageNum(), pageDTO.getPageSize());
        IPage<Orders> page = ordersMapper.selectPage(orders, null);

        PageResult pageResult = new PageResult();
        pageResult.setList(page.getRecords());
        pageResult.setTotal(page.getTotal());

        return pageResult;
    }

    @Override
    public List<OrderVO> getByUserId(Integer id) {

        return ordersMapper.getOrdersByUserId(id);
    }

    @Override
    public List<Orders> getByNotPaid(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user_id", id);
        map.put("status", 0);

        List<Orders> orders = ordersMapper.selectByMap(map);

        if (orders == null) {
            log.error("{}无未支付订单", id);
            return null;
        } else{
            return orders;
        }
    }

    @Override
    public List<Orders> getByPay(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user_id", id);
        map.put("status", 1);

        List<Orders> orders = ordersMapper.selectByMap(map);

        if (orders == null) {
            log.error("{}无未支付订单", id);
            return null;
        } else{
            return orders;
        }
    }

    @Override
    public List<Orders> getByTime(Integer id, String time) {
//        将字符串转化为日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        try {
            LocalDate date = LocalDate.parse(time, formatter);
            System.out.println("转化后："+date);
            LambdaQueryWrapper<Orders> query = new LambdaQueryWrapper<Orders>();
            query.likeRight(Orders::getPaymentTime, date);
            List<Orders> list = ordersMapper.selectList(query);
            if (list.size() == 0){
                System.out.println(list);
                log.error("{}无订单", id);
                return null;
            } else {
                return list;
            }
        } catch (Exception E) {
            log.error("日期格式异常");
            return null;
        }
    }

    @Override
    public List<Orders> getByTimeInterval(String startTime, String endTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate startDate;
        LocalDate endDate;
        LocalDateTime start;
        LocalDateTime end;
        try {
            //将字符串转化为日期格式
            startDate = LocalDate.parse(startTime, formatter);
            endDate = LocalDate.parse(endTime, formatter);
            //将开始日期格式转化为当天日期（年月日时分秒）
            start =   startDate.atStartOfDay();
//            将结束日期转化为次日减去一秒
            end = endDate.atStartOfDay().plusDays(1).minusSeconds(1);
        }catch (Exception e) {
            log.error("日期格式异常");
            return null;
        }
        //执行区间查询
        LambdaQueryWrapper<Orders> query = new LambdaQueryWrapper<Orders>();
        query.ge(Orders::getPaymentTime, start).le(Orders::getPaymentTime, end);
        List<Orders> list = ordersMapper.selectList(query);
        if (list == null){
            log.error("该日期无订单");
            return null;
        } else {
            return list;
        }
    }

    @Override
    public OrderVO getDetails(Integer id) {
        //查询订单数据
        Orders order = ordersMapper.selectById(id);
        if (order == null){
            log.error("订单不存在");
            return null;
        }

        //查询订单详情数据
        List<OrderDetailsVO> orderDetails = orderDetailsMapper.getDetailsList(id);

        System.out.println(orderDetails);
        //将查询到的详情数据复制到订单详情
        OrderVO orderVo = new OrderVO();
        orderVo.setOrderDetailsList(orderDetails);

        System.out.println("订单："+order);

        System.out.println("复制之前："+orderVo);
        BeanUtils.copyProperties(order, orderVo);

        System.out.println("详情："+orderVo);

        return orderVo;
    }

    @Override
    public Boolean delete(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order_id", id);

        int i = orderDetailsMapper.deleteByMap(map);
        int result = ordersMapper.deleteById(id);
        if (i >0 && result > 0){
            return true;
        } else {
            if (result < 0) {
                log.error("订单不存在");
            }            return false;
        }
    }

    @Override
    public OrderPaymentVO getAmount(Integer orderId) {
        QueryWrapper<Orders> query = new QueryWrapper<Orders>();
        query.eq("id", orderId);
        query.eq("pay_status", 0);
        query.eq("status", 1);


        Orders order = ordersMapper.selectOne(query);
        //调用用户消费接口
        User user1 = userService.consume(order.getUserId(), order.getTotalPrice());
        if (user1 == null) {
            log.error("余额不足");
            return null;
        }
        order.setPayStatus(1);
        order.setPaymentTime(LocalDateTime.now());

        User user = userService.getById(order.getUserId());

        //发送支付成功邮件
        commonService.sendPayMessage(user.getEmail(), user.getName(), order.getTotalPrice());
//            修改订单状态
        ordersMapper.updateById(order);

        //复制支付的信息返回
        OrderPaymentVO paymentVO = new OrderPaymentVO();
        BeanUtils.copyProperties(order, paymentVO);

        return paymentVO;
    }

    @Override
    public Orders cancel(Integer id) {
        Orders orders = ordersMapper.selectById(id);
        if (orders == null){
            log.error("订单不存在");
            return null;
        } else if (orders.getPayStatus() == 1) {
            log.error("订单已支付");
            return null;
        } else if(orders.getStatus() == 0) {
            log.error("订单已取消");
            return null;
        } else {
            orders.setStatus(0);
            int i = ordersMapper.updateById(orders);

            if (i > 0){
                return orders;
            } else {
                log.error("修改状态失败");
                return null;
            }
        }
    }

    @Override
    public Orders add(Integer id, Integer staffId) {
        User user = userMapper.selectById(id);

        if (user == null) {
            log.error("用户不存在");
            return null;
        } else {
            Orders orders = new Orders();
            NumberUtils numberUtils = new NumberUtils();

            orders.setUserId(id);
            orders.setCreateTime(LocalDateTime.now());
            orders.setOrderNo(numberUtils.getOrderNumber());
            orders.setStaffId(staffId);
            orders.setTotalPrice(0.00);
            orders.setStatus(1);
            orders.setPayStatus(0);
            int i = ordersMapper.insert(orders);

            if (i > 0){
                return orders;
            } else {
                log.error("订单创建失败");
                return null;
            }
        }
    }

    @Override
    public Orders refund(Integer id) {
        Orders orders = ordersMapper.selectById(id);

        if (orders == null){
            log.error("订单不存在");
            return null;
        } else if(orders.getStatus() == 0) {
            log.error("订单已取消");
            return null;
        } else if (orders.getPayStatus() == 0) {
            log.error("订单未支付");
            return null;
        } else {
            //用户余额与积分
            User user = userMapper.selectById(orders.getUserId());
            user.setBalance(user.getBalance() + orders.getTotalPrice());
            user.setIntegral(user.getIntegral() - orders.getTotalPrice().intValue());
            int i = userMapper.updateById(user);
            if (i <= 0) {
                log.error("用户余额与积分修改失败");
                return null;
            }

            orders.setStatus(0);
            orders.setPayStatus(0);
            int j = ordersMapper.updateById(orders);

            if (j <= 0) {
                log.error("订单状态修改失败");
                return null;
            }
        }

        return orders;
    }

    @Override
    public List<Orders> cancelled() {
       QueryWrapper<Orders> query = new QueryWrapper<Orders>();
       query.eq("status", 0);

        return ordersMapper.selectList(query);
    }

    @Override
    public List<Orders> getByStatus(Integer id, Integer status) {
        QueryWrapper<Orders> query = new QueryWrapper<Orders>();
        query.eq("status", status);
        query.eq("user_id", id);

        return ordersMapper.selectList(query);
    }
}




